package org.example.mrrope.utils;

import java.util.function.Supplier;

public class RetryUtil {

    public static <T> T retry(Supplier<T> supplier, int maxRetries, long delayMillis) throws Exception {
        Exception lastException = null;
        for (int attempt = 1; attempt <= maxRetries; attempt++) {
            try {
                return supplier.get();
            } catch (Exception e) {
                lastException = e;
                System.out.println("Attempt " + attempt + " failed: " + e.getMessage());
                if (attempt < maxRetries) {
                    Thread.sleep(delayMillis);
                }
            }
        }
        throw lastException;
    }

    public static void main(String[] args) {
        try {
            String result = retry(() -> {
                // 这里放置可能会失败的操作
                if (Math.random() > 0.5) {
                    throw new RuntimeException("Operation failed");
                }
                return "Success";
            }, 3, 1000); // 最多重试3次，每次间隔1秒
            System.out.println(result);
        } catch (Exception e) {
            System.err.println("All attempts failed: " + e.getMessage());
        }
    }
}
